package com.easy.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class ApiUtils {
	private static final String API_LINK = "http://api.ndd001.com/do.php?";

	public static String getLogin(String apiname, String apipwd) {
		String test = "1|thisistoken";

		String url = API_LINK + "action=loginIn&name=" + apiname + "&password=" + apipwd;
		String result = sendPost(url);

		return result;
	}

	public static String getPhone(String token) {
		String test = "1|15680747336";

		String url = API_LINK + "action=getPhone&sid=10015,10016&token=" + token;
		String result = sendPost(url);

		return result;
	}

	public static String getSmsCode(String mobile, String token) {

		String url = API_LINK + "action=getMessage&sid=10015,10016&phone=" + mobile + "&token=" + token
				+ "&author=xuebian";
		String result = sendPost(url);

		return result;
	}

	public static String getSmsState(String mobile, String token) {
		String url = API_LINK + "action=getSentMessageStatus&phone=" + mobile + "&sid=10015,10016&token=" + token;
		String result = sendPost(url);
		return result;
	}

	public static String addBlacklist(String mobile, String token) {
		String url = API_LINK + "action=addBlacklist&sid=10015,10016&phone=" + mobile + "&token=" + token;
		String result = sendPost(url);
		return result;
	}

	public static String sendPost(String url) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// �򿪺�URL֮�������
			URLConnection conn = realUrl.openConnection();
			// ����ͨ�õ���������
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// ����POST�������������������

			conn.setDoOutput(true);
			conn.setDoInput(true);
			// ��ȡURLConnection�����Ӧ�������
			out = new PrintWriter(conn.getOutputStream());
			// flush������Ļ���
			out.flush();
			// ����BufferedReader����������ȡURL����Ӧ
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("���� POST ��������쳣��" + e);
			e.printStackTrace();
		}
		// ʹ��finally�����ر��������������

		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}
